/**
 * 编写服务器业务代码
 */

const querystring = require("querystring");
const handleBlogRoute = require("./src/routes/blog.js");
const handleUserRoute = require("./src/routes/user.js");

const handleTokenRoute = require("./src/routes/token.js");

// 处理POST数据
const getPostData = (req) => {
  return new Promise((resolve, reject) => {
    // 不是post请求和json请求格式的不做处理， 直接放行
    if (
      req.method !== "POST" ||
      req.headers["content-type"] !== "application/json"
    ) {
      resolve({});
      return;
    }

    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      if (!postData) {
        resolve({});
        return;
      }

      resolve(JSON.parse(postData));
    });
  });
};

const serverHandler = (req, res) => {
  // 设置响应的格式
  res.setHeader("Content-Type", "application/json");

  // 获取path
  const url = req.url;
  req.path = url.split("?")[0];

  // 解析query
  req.query = querystring.parse(url.split("?")[1]);

  // 处理POST数据
  getPostData(req).then((postData) => {
    req.body = postData;

    // token验证（放行这里修改）
    const tokenResult = handleTokenRoute(req, res);
    if (tokenResult) {
      res.statusCode = tokenResult.status;
      res.end(JSON.stringify(tokenResult));
      return;
    }
      
    // 用户相关的路由
    const userDataPromise = handleUserRoute(req, res);
    if (userDataPromise) {
      userDataPromise.then(userData => {
        res.statusCode = userData.status;
        res.end(JSON.stringify(userData));
      })
      return;
    }

    // 博客相关的路由
    const blogDataPromise = handleBlogRoute(req, res);
    if (blogDataPromise) {
      blogDataPromise.then(blogData => {
        res.statusCode = blogData.status;
        res.end(JSON.stringify(blogData));
      })
      return;
    }

    // 未匹配到 任何路由
    res.statusCode = 404;
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.write("404 Not Found");
    res.end();
  });
};

module.exports = serverHandler;
